package com.yugao.fintech.framework.ip2region.factory;

import com.maxmind.geoip2.DatabaseReader;
import com.yugao.fintech.framework.core.constant.LyCoreConstants;
import com.yugao.fintech.framework.core.http.HttpRequestServletManager;
import com.yugao.fintech.framework.core.utils.IpUtils;
import com.yugao.fintech.framework.ip2region.constants.IpOfflineType;
import com.yugao.fintech.framework.ip2region.handler.Geoip2Handler;
import com.yugao.fintech.framework.ip2region.handler.Ip2RegionOfflineHandler;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Component
@ConditionalOnClass(DatabaseReader.class)
@ConditionalOnProperty(prefix = LyCoreConstants.PROPERTIES_PRE + "ip2region", value = "offline.type", havingValue = IpOfflineType.GEOIP2)
public class Geoip2Offline implements Ip2RegionOfflineFactory {
    @Resource
    private DatabaseReader reader;

    @Override
    public Ip2RegionOfflineHandler create(HttpServletRequest request) {
        String ip = IpUtils.getRequestIp(new HttpRequestServletManager(request));
        return new Geoip2Handler(ip, reader);
    }

    @Override
    public Ip2RegionOfflineHandler create(String ip) {
        return new Geoip2Handler(ip, reader);
    }
}
